13. Anatomy of a Function

Anatomy of a Function

You have seen how to write a function in C++. More generically, a C++ functions consists of a function declaration and a function definition.

Because C++ is statically typed, you need to specify the data types for the function input variables and the data type of whatever the function returns.

// function declaration
returndatatype functionname(datatype variable_a, datatype variable_b, etc.);
// function definition
returndatatype functionname(datatype variable_a, datatype variable_b, etc.) {
     statement_1;
     statement_2;
     etc...

   return returndatatype;
}

Function Definition

Take a look at this function definition:

bool isAutonomous(int x, float y, char z); 

Why is there a bool written before the function name?

SOLUTION: Because the function returns a boolean value

Function Declarations

What would be the input and output of this function?

char myfunction(int x);
SOLUTION: The function would have an integer input and return a character.

Quiz: Write a Function

Write a function, called distance, with three inputs and one output. The inputs are velocity, acceleration and time. The output is the distance traveled over the elapsed time. The equation for calculating distance is:
distance = velocity \times elapsedtime + 0.5 \times acceleration \times elapsedtime \times elapsedtime

This quiz is not graded. You will see some test cases in the main() function to test out your code. To run your code, click on the "Test Run" button.

A solution has been provided in the solution.cpp so that you can compare your results.

Start Quiz:

//TODO: include the iostream part of the standard library

//TODO: declare your function called distance

// Leave the main function as is
int main() {
    
    // TODO: The following are examples you can use to test your code.
    // You will need to uncomment them to get them working.
    
    // std::cout << distance(3, 4, 5) << std::endl;  
    // std::cout << distance(7.0, 2.1, 5.4) << std::endl;
    
    return 0;   
}

//TODO: define your function
//TODO: include the iostream part of the standard library
#include <iostream>

//TODO: declare your function called distance
float distance(float velocity, float acceleration, float time_elapsed);

// Leave the main function as is
int main() {
    
    // TODO: The following are examples you can use to test your code.
    // You will need to uncomment them to get them working.
    
    std::cout << distance(3, 4, 5) << std::endl;  
    std::cout << distance(7.0, 2.1, 5.4) << std::endl;
    
    return 0;   
}

//TODO: define your function
float distance(float velocity, float acceleration, float time_elapsed) {
    return velocity*time_elapsed + 0.5*acceleration*time_elapsed*time_elapsed;
}